package com.yenroc.ho.多线程;

/**
 * synchronized 关键字保证一段代码的原子性
 */
public class MyThread02 {
    public static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread addThread = new Thread(()->{
            for (int i=0; i<10000; i++) {
                synchronized (MyThread02.class) {
                    count += 1;
                }
            }
        });
        Thread decThread = new Thread(()->{
            for (int i=0; i<10000; i++) {
                synchronized (MyThread02.class) {
                    count -= 1;
                }
            }
        });
        addThread.start();
        decThread.start();

        addThread.join();
        decThread.join();

        System.out.print(Thread.currentThread().getName() + "\t count=" + count);
    }
}
